package com.internetCafes.spms.web.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.module.excel.po.ProjectExcel;
import com.internetCafes.spms.common.module.excel.po.ProjectStaticExcel;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.common.utils.StringUtils;
import com.internetCafes.spms.common.utils.entity.page.PageItemDTO;
import com.internetCafes.spms.common.utils.entity.page.PageItemVO;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.web.certificate.model.vo.project.CertificateTransactionOutProjectsVO;
import com.internetCafes.spms.web.certificate.service.CertiTransactionInfoService;
import com.internetCafes.spms.web.certificate.vo.CertiTransactionInfoVo;
import com.internetCafes.spms.web.project.common.ProjectConst;
import com.internetCafes.spms.web.project.entity.ProjectConfig;
import com.internetCafes.spms.web.project.entity.dto.projectconfig.ProjectCertificatePagingDTO;
import com.internetCafes.spms.web.project.entity.dto.projectconfig.ProjectPagingDTO;
import com.internetCafes.spms.web.project.entity.dto.projectconfig.ProjectSaveDTO;
import com.internetCafes.spms.web.project.entity.dto.projectconfig.ProjectUpdateDTO;
import com.internetCafes.spms.web.project.entity.dto.projectstatistics.ProjectStatisticPagingDTO;
import com.internetCafes.spms.web.project.entity.po.ProjectCertificatesPagingPO;
import com.internetCafes.spms.web.project.entity.po.ProjectInfoPO;
import com.internetCafes.spms.web.project.entity.po.ProjectPagingPO;
import com.internetCafes.spms.web.project.entity.vo.projectconfig.ProjectCertificatesPagingVO;
import com.internetCafes.spms.web.project.entity.vo.projectconfig.ProjectFilesVO;
import com.internetCafes.spms.web.project.entity.vo.projectconfig.ProjectInfoVO;
import com.internetCafes.spms.web.project.entity.vo.projectconfig.ProjectPagingVO;
import com.internetCafes.spms.web.project.entity.vo.projectstatistics.ProjectStatisticPagingVO;
import com.internetCafes.spms.web.project.mapper.ProjectConfigMapper;
import com.internetCafes.spms.web.project.service.IProjectConfigService;
import com.internetCafes.spms.web.sys.model.ResourceInfo;
import com.internetCafes.spms.web.sys.service.ResourceInfoService;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import com.sms.common.util.hutool.core.util.ObjectUtil;
import org.nlpcn.commons.lang.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 项目信息管理表 服务实现类
 * </p>
 *
 * @author Zj
 * @since 2021-04-27
 */
@Service
public class ProjectConfigServiceImpl extends ServiceImpl<ProjectConfigMapper, ProjectConfig> implements IProjectConfigService {

    @Autowired
    private ResourceInfoService resourceInfoService;

    @Autowired
    private CertiTransactionInfoService certiTransactionInfoService;


    @Value("${system.remote.url}")
    private String remoteUrl;


    /**
     * 证书借出获取项目列表
     *
     * @return 项目列表
     * @author Zj
     */
    @Override
    public List<CertificateTransactionOutProjectsVO> transactionOutProjects() {
        QueryWrapper<ProjectConfig> queryWrapper = new QueryWrapper<>();
        LocalDateTime currentTime = LocalDateTime.now();
        queryWrapper.eq("delete_flag", 0)
                .and(wrapper -> wrapper.ge("contract_end_time", currentTime)
                        .or()
                        .isNull("contract_end_time"));

        List<ProjectConfig> projects = list(queryWrapper);
        List<CertificateTransactionOutProjectsVO> results = projects.stream()
                .map(project -> new CertificateTransactionOutProjectsVO(project.getId(), project.getProjectName()))
                .collect(Collectors.toList());
        return results;
    }

    /**
     * 项目信息导出
     *
     * @return 项目信息列表
     * @author Zj
     */
    @Override
    public List<ProjectExcel> exportProjectInfos() {
        List<ProjectExcel> projectExcels = new ArrayList<>();

        List<ProjectPagingPO> projectPagingPOS = baseMapper.listAllJoinEmployee();

        if (CollectionUtil.isNotEmpty(projectPagingPOS)) {
            projectExcels = projectPagingPOS.stream()
                    .map(project -> {
                        ProjectExcel projectExcel = new ProjectExcel();
                        BeanUtils.copyProperties(project, projectExcel);
                        projectExcel.setStatus(ProjectConst.StatusTag.BUILDING.getValueByTag(project.getStatusTag()));
                        return projectExcel;
                    })
                    .collect(Collectors.toList());
        }
        return projectExcels;
    }

    /**
     * 项目统计导出excel
     *
     * @return 导出相关excel信息
     * @author Zj
     */
    @Override
    public List<ProjectStaticExcel> exportProjectStatic() {
        List<ProjectPagingPO> projectPagingPOS = baseMapper.listAllJoinEmployee();

        List<ProjectStaticExcel> projectStaticExcels = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(projectPagingPOS)) {
            List<Long> projectIds = projectPagingPOS.stream()
                    .map(ProjectPagingPO::getId)
                    .collect(Collectors.toList());
            HashMap<String, Object> params = new HashMap<>();
            params.put("projectId", projectIds);
            List<CertiTransactionInfoVo> certificates = certiTransactionInfoService.selectByJobParams(params);
            Map<Long, List<CertiTransactionInfoVo>> certificatesGroupByProjectId = certificates.stream()
                    .collect(Collectors.groupingBy(CertiTransactionInfoVo::getProjectId));
            // 数据封装
            projectStaticExcels = projectPagingPOS.stream()
                    .map(record -> {
                        ProjectStaticExcel recordResult = new ProjectStaticExcel();
                        List<CertiTransactionInfoVo> certificatesOfRecord = certificatesGroupByProjectId.get(record.getId());
                        BeanUtils.copyProperties(record, recordResult);
                        String certificatesInfo = "暂无证书";
                        int amount = 0;
                        if (CollectionUtil.isNotEmpty(certificatesOfRecord)) {
                            Map<String, List<CertiTransactionInfoVo>> certificatesGroupByIdType = certificatesOfRecord.stream()
                                    .collect(Collectors.groupingBy(CertiTransactionInfoVo::getIdType));
                            // 获取项目的相关证书列表，计算证书内容，证书数量等
                            StringBuilder stringBuilder = new StringBuilder();
                            for (Map.Entry<String, List<CertiTransactionInfoVo>> entry : certificatesGroupByIdType.entrySet()) {
                                stringBuilder.append(entry.getKey());
                                stringBuilder.append(entry.getValue().size());
                                stringBuilder.append("本;");
                            }
                            // 去除最后一个符号
                            certificatesInfo = stringBuilder.substring(0, stringBuilder.length());
                            amount = certificatesOfRecord.size();
                        }
                        recordResult.setCertificates(certificatesInfo);
                        recordResult.setCertificateAmount(amount);
                        recordResult.setStatus(ProjectConst.StatusTag.BUILDING.getValueByTag(record.getStatusTag()));
                        return recordResult;
                    })
                    .collect(Collectors.toList());
        }
        return projectStaticExcels;
    }

    /**
     * 项目证书分页列表
     *
     * @param dto 请求参数
     * @return 项目证书列表
     * @author Zj
     */
    @Override
    public PageItemVO<ProjectCertificatesPagingVO> certificatesPaging(PageItemDTO<ProjectCertificatePagingDTO> dto) {
        Page<ProjectConfig> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        ProjectCertificatePagingDTO conditions = dto.getConditions();
        if (ObjectUtil.isNull(conditions.getProjectId())) {
            throw new RRException("参数错误");
        }
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        // 排序
        if (StringUtil.isNotBlank(dto.getOrderBy())) {
            if ("desc".equals(dto.getInOrder())) {
                queryWrapper
                        .orderByDesc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            } else {
                queryWrapper
                        .orderByAsc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            }
        } else {
            queryWrapper.orderByDesc("id");
        }
        Page<ProjectCertificatesPagingPO> pageResult = baseMapper.pageCerificatesOfProject(page, conditions.getProjectId(), queryWrapper);
        // 分页数据封装
        PageItemVO<ProjectCertificatesPagingVO> result = new PageItemVO<>();
        BeanUtils.copyProperties(pageResult, result);
        List<ProjectCertificatesPagingPO> records = pageResult.getRecords();

        Date currentTime = new Date();
        List<ProjectCertificatesPagingVO> results = records.stream()
                .map(record -> {
                    ProjectCertificatesPagingVO certificateVO = new ProjectCertificatesPagingVO();
                    BeanUtils.copyProperties(record, certificateVO);
                    if (ObjectUtil.isNotNull(record.getValidityEndTime())) {
                        if (currentTime.after(record.getValidityEndTime())) {
                            certificateVO.setWarningFlag(3);
                            certificateVO.setWarningInfo("已到期");
                        } else {
                            long dates = Duration.between(currentTime.toInstant(), record.getValidityEndTime().toInstant()).toDays();
                            if (dates < 30) {
                                certificateVO.setWarningFlag(2);
                                certificateVO.setWarningInfo("还有" + (dates + 1) + "到期");
                            } else {
                                certificateVO.setWarningFlag(1);
                                certificateVO.setWarningInfo("未到期");
                            }
                        }
                    } else {
                        certificateVO.setWarningFlag(1);
                        certificateVO.setWarningInfo("未到期");
                    }
                    return certificateVO;
                })
                .collect(Collectors.toList());
        result.setRecords(results);
        return result;
    }

    /**
     * 项目统计列表
     *
     * @param dto 请求参数
     * @return 数据列表
     * @author Zj
     */
    @Override
    public PageItemVO<ProjectStatisticPagingVO> statisticPaging(PageItemDTO<ProjectStatisticPagingDTO> dto) {
        Page<ProjectConfig> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        QueryWrapper<ProjectConfig> projectConfigQueryWrapper = new QueryWrapper<>();
        ProjectStatisticPagingDTO conditions = dto.getConditions();
        // 分页条件封装
        projectConfigQueryWrapper
                .like(StringUtil.isNotBlank(conditions.getProjectName()), "xpc.project_name", conditions.getProjectName())
                .eq(ObjectUtil.isNotNull(conditions.getStatusTag()) && !conditions.getStatusTag().equals(0), "xpc.status_tag", conditions.getStatusTag())
                .ge(ObjectUtil.isNotNull(conditions.getContractStartTime()), "xpc.contract_start_time", conditions.getContractStartTime())
                .le(ObjectUtil.isNotNull(conditions.getContractEndTime()), "xpc.contract_end_time", conditions.getContractEndTime())
                .ge(ObjectUtil.isNotNull(conditions.getActualStartTime()), "xpc.actual_start_time", conditions.getActualStartTime())
                .le(ObjectUtil.isNotNull(conditions.getActualEndTime()), "xpc.actual_end_time", conditions.getActualEndTime())
                .like(ObjectUtil.isNotNull(conditions.getEmployeeName()), "tei.`name`", conditions.getEmployeeName())
                .apply(StringUtil.isNotBlank(conditions.getInnerEmployeeName()), "xpc.id IN (\n" +
                        "                SELECT\n" +
                        "                tcti.project_id\n" +
                        "                FROM t_certi_transaction_info tcti\n" +
                        "                LEFT JOIN t_certificate_info tci ON tcti.certificate_id = tci.id\n" +
                        "                LEFT JOIN t_employee_info tei_2 ON tei_2.id = tci.employee_id\n" +
                        "                WHERE tei_2.`name` like CONCAT('%',{0},'%')\n" +
                        "                )", conditions.getInnerEmployeeName())
                .apply(StringUtil.isNotBlank(conditions.getInnerCertificateNo()), "xpc.id IN (\n" +
                        "                SELECT\n" +
                        "                tcti.project_id\n" +
                        "                FROM t_certi_transaction_info tcti\n" +
                        "                LEFT JOIN t_certificate_info tci ON tcti.certificate_id = tci.id\n" +
                        "                WHERE tci.certificate_no = {0}\n" +
                        "                )", conditions.getInnerCertificateNo())
        ;
        // 排序
        if (StringUtil.isNotBlank(dto.getOrderBy())) {
            if ("status".equals(dto.getOrderBy())) {
                dto.setOrderBy("status_tag");
            }
            // 排序字段证书数量特殊处理
            if ("certificateAmount".equals(dto.getOrderBy())) {
                dto.setOrderBy("cert_amount_group_by_project_id.amount");
            }
            if ("desc".equals(dto.getInOrder())) {
                projectConfigQueryWrapper
                        .orderByDesc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            } else {
                projectConfigQueryWrapper
                        .orderByAsc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            }
        } else {
            projectConfigQueryWrapper.orderByDesc("id");
        }

        IPage<ProjectPagingPO> pageResult = baseMapper.pageJoinEmployee(page, projectConfigQueryWrapper);
        // 分页数据封装
        PageItemVO<ProjectStatisticPagingVO> result = new PageItemVO<>();
        BeanUtils.copyProperties(pageResult, result);
        List<ProjectPagingPO> records = pageResult.getRecords();

        if (CollectionUtil.isNotEmpty(records)) {
            // 获取对应的所有证书
            List<Long> projectIds = records.stream()
                    .map(ProjectPagingPO::getId)
                    .collect(Collectors.toList());
            HashMap<String, Object> params = new HashMap<>();
            params.put("projectIds", projectIds);
            params.put("type", CommonConstants.CertiTransactionInfoType.Transaction);
            params.put("statusTag", CommonConstants.CertiTransactionStatusTags.IN_PROGRESS);
            List<CertiTransactionInfoVo> certificates = certiTransactionInfoService.selectTransInfoAndIdtypeByParams(params);
            Map<Long, List<CertiTransactionInfoVo>> certificatesGroupByProjectId = certificates.stream()
                    .collect(Collectors.groupingBy(CertiTransactionInfoVo::getProjectId));
            // 数据封装
            List<ProjectStatisticPagingVO> recordsResult = records.stream()
                    .map(record -> {
                        ProjectStatisticPagingVO recordResult = new ProjectStatisticPagingVO();
                        List<CertiTransactionInfoVo> certificatesOfRecord = certificatesGroupByProjectId.get(record.getId());
                        BeanUtils.copyProperties(record, recordResult);
                        String certificatesInfo = "暂无证书";
                        int amount = 0;
                        if (CollectionUtil.isNotEmpty(certificatesOfRecord)) {
                            Map<String, List<CertiTransactionInfoVo>> certificatesGroupByIdType = certificatesOfRecord.stream()
                                    .collect(Collectors.groupingBy(CertiTransactionInfoVo::getIdType));
                            // 获取项目的相关证书列表，计算证书内容，证书数量等
                            StringBuilder stringBuilder = new StringBuilder();
                            for (Map.Entry<String, List<CertiTransactionInfoVo>> entry : certificatesGroupByIdType.entrySet()) {
                                stringBuilder.append(entry.getKey());
                                stringBuilder.append(entry.getValue().size());
                                stringBuilder.append("本;");
                            }
                            // 去除最后一个符号
                            certificatesInfo = stringBuilder.substring(0, stringBuilder.length());
                            amount = certificatesOfRecord.size();
                        }
                        recordResult.setCertificates(certificatesInfo)
                                .setCertificateAmount(amount)
                                .setStatus(ProjectConst.StatusTag.BUILDING.getValueByTag(recordResult.getStatusTag()));
                        return recordResult;
                    })
                    .collect(Collectors.toList());
            result.setRecords(recordsResult);
        }
        return result;
    }

    /**
     * 获取项目详情
     *
     * @param id 项目id
     * @return 项目详情
     * @author Zj
     */
    @Override
    public ProjectInfoVO info(Long id) {
        ProjectInfoPO projectPO = baseMapper.infoJoinEmployee(id);
        if (ObjectUtil.isNull(projectPO)) {
            throw new RRException("记录不存在");
        }
        ProjectInfoVO projectInfoVO = new ProjectInfoVO();
        BeanUtils.copyProperties(projectPO, projectInfoVO);

        // 获取附件列列表
        HashMap<String, Object> params = new HashMap<>();
        params.put("moduleId", id);
        params.put("moduleCode", CommonConstants.ResourceInfo_PIC_ProjectInfo);
        List<ResourceInfo> resources = resourceInfoService.query(params);
        List<ProjectFilesVO> files = resources.stream()
                .map(file ->
                        new ProjectFilesVO(remoteUrl, file.getFileName(), file.getPath()))
                .collect(Collectors.toList());
        projectInfoVO.setStatus(ProjectConst.StatusTag.BUILDING.getValueByTag(projectInfoVO.getStatusTag()));
        projectInfoVO.setFileList(files);

        return projectInfoVO;
    }

    /**
     * 作废项目
     *
     * @param id id
     * @author Zj
     */
    @Override
    public void deleteById(Long id) {
        ProjectConfig projectUpdateDO = new ProjectConfig();
        projectUpdateDO
                .setId(id)
                .setDeleteFlag(1);
        updateById(projectUpdateDO);
    }

    /**
     * 数据更新
     *
     * @param dto 更新参数
     * @author Zj
     */
    @Override
    public void update(ProjectUpdateDTO dto) {
        // 1-必传参数校验
        if (StringUtils.isEmpty(dto.getProjectName())
                || dto.getStatusTag() == null || dto.getDeptId() == null
                || dto.getEmployeeId() == null) {
            throw new RRException("参数错误");
        }
        if (ObjectUtil.isNull(dto.getId())) {
            throw new RRException("记录不存在");
        }
        // 2-数据更新
        Long currentUserId = ShiroUtils.getUserId();
        Date currentTime = new Date();
        ProjectConfig projectConfigUpdateDO = new ProjectConfig();
        BeanUtils.copyProperties(dto, projectConfigUpdateDO);
        projectConfigUpdateDO
                .setUpdateBy(currentUserId)
                .setUpdateTime(currentTime);
        updateById(projectConfigUpdateDO);
        // 3-更新附件文件 文件删除有问题暂时停用删除
        // 问题已解决，因需求问题暂时不提供附件修改 by Zj 20210508
       /* List<String> filePaths = dto.getFileList();
        List<ResourceInfo> resourceInfos = filePaths.stream()
                .map(filePath -> new ResourceInfo(currentUserId,
                        CommonConstants.ResourceInfo_PIC_ProjectInfo, dto.getId(),
                        CommonConstants.ResourceInfo_Path_Prefix + File.separator + filePath))
                .collect(Collectors.toList());
        resourceInfoService.updateBatch(
                resourceInfos,
                CommonConstants.ResourceInfo_PIC_ProjectInfo,
                dto.getId()
        );*/
    }

    /**
     * 分页接口
     *
     * @param dto 分页请求参数
     * @return 分页数据
     * @author Zj
     */
    @Override
    public PageItemVO<ProjectPagingVO> page(PageItemDTO<ProjectPagingDTO> dto) {
        Page<ProjectConfig> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        QueryWrapper<ProjectConfig> projectConfigQueryWrapper = new QueryWrapper<>();
        ProjectPagingDTO conditions = dto.getConditions();
        projectConfigQueryWrapper
                .like(StringUtil.isNotBlank(conditions.getProjectName()), "xpc.project_name", conditions.getProjectName())
                .eq(ObjectUtil.isNotNull(conditions.getStatusTag()) && !conditions.getStatusTag().equals(0), "status_tag", conditions.getStatusTag())
                .ge(ObjectUtil.isNotNull(conditions.getContractStartTime()), "xpc.contract_start_time", conditions.getContractStartTime())
                .le(ObjectUtil.isNotNull(conditions.getContractEndTime()), "xpc.contract_end_time", conditions.getContractEndTime())
                .ge(ObjectUtil.isNotNull(conditions.getActualStartTime()), "xpc.actual_start_time", conditions.getActualStartTime())
                .le(ObjectUtil.isNotNull(conditions.getActualEndTime()), "xpc.actual_end_time", conditions.getActualEndTime())
                .like(ObjectUtil.isNotNull(conditions.getEmployeeName()), "tei.`name`", conditions.getEmployeeName())
                .eq(ObjectUtil.isNotNull(conditions.getInvalidFlag()), "xpc.delete_flag", conditions.getInvalidFlag())
                .apply(StringUtil.isNotBlank(conditions.getInnerEmployeeName()), "xpc.id IN (\n" +
                        "                SELECT\n" +
                        "                tcti.project_id\n" +
                        "                FROM t_certi_transaction_info tcti\n" +
                        "                LEFT JOIN t_certificate_info tci ON tcti.certificate_id = tci.id\n" +
                        "                LEFT JOIN t_employee_info tei_2 ON tei_2.id = tci.employee_id\n" +
                        "                WHERE tei_2.`name` like CONCAT('%',{0},'%')\n" +
                        "                )", conditions.getInnerEmployeeName())
                .apply(StringUtil.isNotBlank(conditions.getInnerCertificateNo()), "xpc.id IN (\n" +
                        "                SELECT\n" +
                        "                tcti.project_id\n" +
                        "                FROM t_certi_transaction_info tcti\n" +
                        "                LEFT JOIN t_certificate_info tci ON tcti.certificate_id = tci.id\n" +
                        "                WHERE tci.certificate_no = {0}\n" +
                        "                )", conditions.getInnerCertificateNo());
        // 封装排序条件
        if (StringUtil.isNotBlank(dto.getOrderBy())) {
            if ("status".equals(dto.getOrderBy())) {
                dto.setOrderBy("statusTag");
            }
            if ("desc".equals(dto.getInOrder())) {
                projectConfigQueryWrapper
                        .orderByDesc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            } else {
                projectConfigQueryWrapper
                        .orderByAsc(com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(dto.getOrderBy()));
            }
        } else {
            projectConfigQueryWrapper.orderByDesc("id");
        }

        IPage<ProjectPagingPO> pageResult = baseMapper.pageJoinEmployee(page, projectConfigQueryWrapper);
        // 分页数据封装
        PageItemVO<ProjectPagingVO> result = new PageItemVO<>();
        BeanUtils.copyProperties(pageResult, result);
        List<ProjectPagingPO> records = pageResult.getRecords();
        // 获取当前天
        Date now = new Date();
        List<ProjectPagingVO> recordsResult = records.stream()
                .map(record -> {
                    ProjectPagingVO recordResult = new ProjectPagingVO();
                    BeanUtils.copyProperties(record, recordResult);
                    // 到期时间封装
                    Date contractEndTime = record.getContractEndTime();
                    if (ObjectUtil.isNotNull(contractEndTime)) {
                        if (contractEndTime.before(now)) {
                            recordResult.setExpireFlag(3);
                            recordResult.setExpireInfo("已到期");
                        } else {
                            long dates = Duration.between(now.toInstant(), contractEndTime.toInstant()).toDays();
                            if (dates > 29L) {
                                recordResult.setExpireFlag(1);
                                recordResult.setExpireInfo("未到期");
                            } else {
                                recordResult.setExpireFlag(2);
                                recordResult.setExpireInfo("还有" + (dates + 1) + "天到期");
                            }
                        }
                    }
                    // 证书状态
                    recordResult.setStatus(ProjectConst.StatusTag.BUILDING.getValueByTag(recordResult.getStatusTag()));
                    return recordResult;
                })
                .collect(Collectors.toList());
        result.setRecords(recordsResult);
        return result;
    }

    /**
     * 项目新增
     *
     * @param dto 新增参数
     * @author Zj
     */
    @Override
    public void save(ProjectSaveDTO dto) {
        // 1-必传参数校验
        if (StringUtils.isEmpty(dto.getProjectName())
                || dto.getStatusTag() == null || dto.getDeptId() == null
                || dto.getEmployeeId() == null) {
            throw new RRException("参数错误");
        }
        // 2-保存证书信息
        Long currentUserId = ShiroUtils.getUserId();
        Date currentTime = new Date();
        ProjectConfig projectSaveDO = new ProjectConfig();
        BeanUtils.copyProperties(dto, projectSaveDO);
        projectSaveDO.setDeleteFlag(0)
                .setCreateBy(currentUserId)
                .setCreateTime(currentTime);
        save(projectSaveDO);
        // 3-保存图片
        if (CollectionUtil.isEmpty(dto.getFileList())) {
            return;
        }
        List<String> filePaths = dto.getFileList();
        List<ResourceInfo> resourceInfos = filePaths.stream()
                .map(filePath -> new ResourceInfo(currentUserId,
                        CommonConstants.ResourceInfo_PIC_ProjectInfo, projectSaveDO.getId(),
                        CommonConstants.ResourceInfo_Path_Prefix + File.separator + filePath))
                .collect(Collectors.toList());
        resourceInfoService.saveBatch(resourceInfos);
    }
}
